package com.framework.core.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;

import com.framework.core.beanfactory.MyBeanFactory;
import com.framework.core.dispacher.ControlDispatcher;
import com.framework.core.domain.Control;
import com.framework.core.utils.InitConfigUtils;
import com.framework.core.utils.InjectServletUrlPattern;
import com.framework.core.utils.PropertiesUtils;
import com.framework.core.utils.RequestMappingUtils;
import com.framework.core.utils.SqlMappingUtils;
import com.framework.core.utils.StringUtils;

/**
 * 加载配置文件
 * 
 * @author Rose 2017年9月13日
 */
@WebServlet(urlPatterns = "*.do")
public class InitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private ServletContext servletContext;
	private RequestMappingUtils requestMappingUtils;
	private PropertiesUtils propertiesUtils;

	private String charset;

	public InitServlet() {
		super();
	}

	static {

	}

	public void init(ServletConfig config) throws ServletException {

		System.out.println("InitServlet：初始化！");

		// servlet上下文
		this.servletContext = config.getServletContext();
		// mapping上下文
		this.requestMappingUtils = RequestMappingUtils.getInstance();
		// properties上下文
		this.propertiesUtils = PropertiesUtils.getInstance();

		// 字符编码
		String initParameter = config.getInitParameter("charset");
		// 判断是否为空
		if (StringUtils.isNotEmpty(initParameter)) {
			this.charset = initParameter;
		} else {
			// 默认字符集
			this.charset = "UTF-8";
		}
		// 加载xmlmapping配置文件--已废弃
		// String xmlconfigpath = config.getInitParameter("xmlconfig");

		// 加载propertiesconfig配置文件
		// String propertiesconfigpath =
		// config.getInitParameter("propertiesconfig");
		String propertiesconfigpath = "application.properties";
		// 类路径
		String path = this.getClass().getClassLoader().getResource("").getPath();
		try {
			// 已废弃
			// Map<String, Object> xmlMap =
			// InitConfigUtils.getXMLRequestMappingConfig(path + xmlconfigpath);
			// servletContext.setAttribute("xmlMap", xmlMap);
			// requestMappingUtils.setMap(xmlMap);

			Map<String, Object> propertiesMap = InitConfigUtils.getPropertiesConfig(path + propertiesconfigpath);
			// servletContext.setAttribute("propertiesMap", propertiesMap);
			propertiesUtils.setMap(propertiesMap);
			// 扫描组件--controller+service--
			MyBeanFactory.beanScanner(propertiesMap.get("basescanpackage").toString());
			// 扫描xmlsql
			Map<String, Map<String, Object>> sqlMap = InitConfigUtils
					.getXMLSqlMappingConfig(propertiesMap.get("sqlscanbasepackage").toString());
			SqlMappingUtils.setMap(sqlMap);
			// 尝试注入urlPattern
			try {
				InjectServletUrlPattern.getInstance().doInject(propertiesMap.get("request.url.patterm").toString(), this);
			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (DocumentException | IOException | ClassNotFoundException e) {
			e.printStackTrace();
			System.err.println("初始化配置文件失败！");
		}

		// ServletContext servletContext = config.getServletContext();
		// String realPath = servletContext.getRealPath("/");
		// try {
		//
		// InitControllerConfig.getConfig(realPath + "/WEB-INF/classes/" +
		// configpath);
		//
		// } catch (DocumentException e) {
		// e.printStackTrace();
		// }

	}

	public void destroy() {
		System.out.println("InitServlet：销毁！");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 解决乱码
		response.setContentType("text/html; charset=" + charset);
		// 截取请求url
		String requestURL = request.getRequestURI();
		String projectNamePath = "/" + servletContext.getServletContextName();
		requestURL = requestURL.replaceAll(projectNamePath, "").trim().replace(".do", "").trim();
		try {
			// 检测是否存在此url
			// Control control = xMLMappingUtils.checkUrl(requestURL);
			Control control = (Control) requestMappingUtils.getControllerByName(requestURL);
			if (null == control) {
				request.setAttribute("errMsg", "找不到对应的requestmapping");
				request.getRequestDispatcher(
						ControlDispatcher.prefix + ControlDispatcher.errPath + ControlDispatcher.suffix)
						.forward(request, response);
			} else {
				// 执行请求操作
				new ControlDispatcher(request, response, servletContext).builder(control);
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errMsg", "找不到对应的requestmapping");
			request.getRequestDispatcher(
					ControlDispatcher.prefix + ControlDispatcher.errPath + ControlDispatcher.suffix)
					.forward(request, response);
		}
		// response.getWriter().write(requestURI);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
